import { defineComponent, onMounted, watch, onUnmounted } from "vue";
// import debounce from "lodash/debounce";
import { addListener, removeListener } from "resize-detector";
// const INIT_TRIGGERS = ["theme", "initOptions", "autoresize"];
// const REWATCH_TRIGGERS = ["manualUpdate", "watchShallow"];
export default defineComponent({
  name: "ECharts",
  props: {
    options: {
      type: Object,
      default: () => {
        return {};
      },
    },
    theme: {
      type: String || Object,
    },
    initOptions: {
      type: Object,
    },
    group: {
      type: String,
    },
    autoresize: {
      type: Boolean,
    },
    watchShallow: {
      type: Boolean,
    },
    manualUpdate: {
      type: Boolean,
    },
    onHandleClick: {
      type: Function,
    },
  },
  setup(props, { emit }) {
    const {
      // options,
      theme,
      initOptions,
      group,
      // autoresize,
      // watchShallow,
      // manualUpdate
    } = props;
    let dom: HTMLElement;
    let chart: any;
    const init = () => {
      if (chart && chart.setOption) {
        chart.setOption(props.options || {}, true);
        return;
      }
      // @ts-ignore
      chart = window.echarts.init(dom, theme, initOptions);
      if (group) {
        chart.group = group;
      }
      chart.setOption(props.options || {}, true);
      chart.on("click", (params: any) => {
        emit("handleClick", params);
      });
      addListener(dom, __resizeHandler);
    };
    const __resizeHandler = () => {
      chart = {};
      init();
    };
    // const state = reactive({
    //   lastArea: 0
    // });

    const getDom = (curDom: any) => {
      dom = curDom;
    };

    watch(props.options, () => {
      init();
    });

    onMounted(() => {
      init();
    });

    // onUnmounted(() => {
    //   removeListener(dom, __resizeHandler);
    // });
    return () => {
      return <div class="echarts" ref={getDom}></div>;
    };
  },
});
